package com.wayne.blog.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wayne.blog.dto.RegisterDTO;
import com.wayne.blog.entity.User;
import com.wayne.blog.mapper.UserMapper;
import com.wayne.blog.service.RoleService;
import com.wayne.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

/**
 * 用户服务实现类
 * @author Lang
 * @since 2024/06/06
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleService roleService;

    @Override
    @Transactional
    public void register(RegisterDTO registerDTO) {
        // 检查用户名是否已存在
        if (userMapper.findByUsername(registerDTO.getUsername()) != null) {
            throw new RuntimeException("用户名已存在");
        }

        // 检查邮箱是否已存在
        if (userMapper.findByEmail(registerDTO.getEmail()) != null) {
            throw new RuntimeException("邮箱已被注册");
        }

        // 创建新用户
        User user = new User();
        user.setUsername(registerDTO.getUsername());
        user.setPassword(DigestUtils.md5DigestAsHex(registerDTO.getPassword().getBytes()));
        user.setEmail(registerDTO.getEmail());
        user.setNickname(registerDTO.getNickname());
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        user.setEnabled(true);

        // 保存用户
        userMapper.insert(user);
    }

    @Override
    public String login(String username, String password) {
        User user = userMapper.findByUsername(username);
        if (user != null && user.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes()))) {
            // 登录成功，使用Sa-Token进行登录
            StpUtil.login(user.getId());
            return StpUtil.getTokenValue();
        }
        return null;
    }

    @Override
    public void logout() {
        StpUtil.logout();
    }

    @Override
    public User getCurrentUser() {
        // 获取当前登录用户ID
        Long userId = StpUtil.getLoginIdAsLong();
        if (userId != null) {
            return userMapper.selectById(userId);
        }
        return null;
    }

    @Override
    public User getByUsername(String username) {
        User user = userMapper.findByUsername(username);
        if (user != null) {
            user.setRoles(roleService.getRolesByUserId(user.getId()));
        }
        return user;
    }

    @Override
    public User getById(Long id) {
        User user = baseMapper.selectById(id);
        if (user != null) {
            user.setRoles(roleService.getRolesByUserId(id));
        }
        return user;
    }
} 